package com.md.api.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.md.api.common.config.RedisKeys;
import com.md.api.common.utils.DateUtils;
import com.md.api.common.utils.IdUtil;
import com.md.api.common.utils.RedisUtil;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.enums.CouponType;
import com.md.api.service.WxService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author liujie
 * @ClassName WxServiceImpl
 **/

@Slf4j
@Service
public class WxServiceImpl implements WxService {

    @Resource
    RedisUtil redisUtil;
    @Resource
    WxMaService wxMaService;
    @Resource
    UserMapper userMapper;
    @Resource
    UserPointRecordMapper pointRecordMapper;
    @Resource
    UserCouponRecordMapper couponRecordMapper;
    @Resource
    CouponInfoMapper couponInfoMapper;
    @Override
    public HttpResult getOpenId(WxMiniLoginReq wxMiniLoginReq) {
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxMiniLoginReq.getCode());
            return new HttpResult(session.getOpenid());
        } catch (WxErrorException e) {
            log.error("获取微信授权信息失败：{}", e.getMessage(), e);
            return HttpResult.fail("小程序登陆失败！");
        }
    }

    @Override
    public HttpResult login(WxMiniLoginReq wxMiniLoginReq) {
        try {

            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxMiniLoginReq.getCode());
            // 调用微信 API 获取用户的手机号
            WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), wxMiniLoginReq.getEncryptedData(), wxMiniLoginReq.getIvStr());
            log.error("获取微信手机号：{}", phoneInfo.toString());
            String phoneNumber = phoneInfo.getPhoneNumber();

            // 将用户信息保存到数据库中
            //查询是否存在，不存在则新增用户
            UserInfo user = userMapper.getByUserId(session.getOpenid());
            if (user == null) {
                user = new UserInfo();
                user.setUserId(session.getOpenid());
                user.setNickName(wxMiniLoginReq.getNickName());
                user.setHeadUrl(wxMiniLoginReq.getHeadUrl());
                user.setPhone(phoneNumber);
                userMapper.register(user);
                //赠送入门优惠券
                List<CouponInfo> coupons = couponInfoMapper.getByCouponType(CouponType.INTRODUCTION_COUPON.value());
                for (CouponInfo coupon:coupons) {
                    UserCouponRecord couponRecord = new UserCouponRecord();
                    String couponRecordId = IdUtil.uuid();
                    couponRecord.setCouponId(coupon.getCouponId());
                    couponRecord.setUserId(session.getOpenid());
                    couponRecord.setCouponRecordId(couponRecordId);
                    couponRecord.setValidityDate(DateUtils.add(new Date(), Calendar.DATE, coupon.getValidityDay()));
                    couponRecordMapper.insert(couponRecord);
                }
                user.setCouponCount(coupons.size());
            } else {
                user.setNickName(wxMiniLoginReq.getNickName());
                user.setHeadUrl(wxMiniLoginReq.getHeadUrl());
//                user.setCountry(country);
//                user.setProvince(province);
//                user.setCity(city);
                user.setPhone(phoneNumber);
                userMapper.updateBase(user);
                //积分数
                Double point = pointRecordMapper.getPoint(session.getOpenid());
                user.setPoint(null==point?0:point);
                //优惠券数量
                List<UserCouponRecord> userCouponRecords = couponRecordMapper.myCoupon(session.getOpenid(), 0,null);
                user.setCouponCount(userCouponRecords.size());
            }
//            String accessToken = wxMaService.getAccessToken();
            String accessToken = IdUtil.uuid();
            user.setToken(accessToken);

//            iMinOperationLogService.insertMinOperationLog(session.getOpenid(), minUser.getUserNickName(), "小程序登陆");
            redisUtil.set(RedisKeys.getUserTokenInfoKey(accessToken),user);
            return new HttpResult(user);
        } catch (WxErrorException e) {
            log.error("获取微信授权信息失败：{}", e.getMessage(), e);
            return HttpResult.fail("小程序登陆失败！");
        }
    }

}
